package com.changli05.compare.comparator;

import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

public class ComparatorTest {
    @Test
    public void test() {
        Product[] p = new Product[6];

        p[0] = new Product("RedMiK80Pro",5023);
        p[1] = new Product("HonorX9",8900);
        p[2] = new Product("HuaweiP50",5990);
        p[3] = new Product("HuaweiMagic9",5010);
        p[4] = new Product("Iphone16ProMax",5010);
        p[5] = new Product("XiaoMi13ProMax",5300);

        Comparator comparator = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Product && o2 instanceof Product) {
                    Product p1 = (Product) o1;
                    Product p2 = (Product) o2;
//                    return p1.getPrice() - p2.getPrice();
                    return Double.compare(p1.getPrice(), p2.getPrice());
                }
                throw new RuntimeException("类型不匹配！！！");
            }
        };
        Comparator comparator1 = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Product && o2 instanceof Product) {
                    Product p1 = (Product) o1;
                    Product p2 = (Product) o2;
                    return p1.name.compareTo(p2.name);
                }
                throw new RuntimeException("类型不匹配！！！");
            }
        };
        Arrays.sort(p,comparator1);
        for (int i = 0; i < p.length; i++) {
            System.out.println(p[i]);

        }

    }
}
